import React, {Component} from 'react';
import {View, StyleSheet, Text, TouchableOpacity} from 'react-native';
import Dog from "../entity/Dog";



export default class Root extends Component {
    mDog;
    constructor() {
        super();
        this.state = {
            datas: [],
        };
        this.mDog = new Dog().open();
    }

    componentWillMount(){
        this.mDog.select(null)
            .then((list)=>{
                this.setState({
                    datas: list
                })
            });
    }

    render() {
        return (
            <View style={styles.container}>
                <View style={{flexDirection: 'column'}}>
                    <TouchableOpacity style={{margin: 15,}} onPress={() => this.save()}>
                        <Text style={styles.style_text}>存储数据</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={{margin: 15,}} onPress={() => this.change()}>
                        <Text style={styles.style_text}>更改数据</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={{margin: 15,}} onPress={() => this.delete()}>
                        <Text style={styles.style_text}>删除数据</Text>
                    </TouchableOpacity>
                </View>
                <View style={{flexDirection: 'column'}}>
                    {this.getItem(this.state.datas)}
                </View>
            </View>
        );
    }

    componentWillUnmount(){
        this.mDog.close();
    }

    save = () => {
        new Dog().insert({})
            .then(() => {
                return this.mDog.select(null);
            }).then((list) => {
            this.setState({
                datas: list
            })
        });
    };

    change = () => {
        Object.assign(this.mDog,this.state.datas[0]);
        this.mDog.name="change";
        this.mDog.update({_id:this.mDog._id})
            .then(()=>{
                return this.mDog.select(null);
            }).then((list)=>{
                this.setState({
                    datas: list
                })
        });
    };

    delete = () => {
        Object.assign(this.mDog,this.state.datas[0])
            .delete({_id:this.mDog._id})
            .then(()=>{
                return this.mDog.select(null);
            }).then((list)=>{
                this.setState({
                    datas: list
                })
            });
    };


    getItem = (dogs) => {
        return (dogs.map((dog, i) => {
            return (<Text style={{fontSize: 17, color: 'black'}} key={i}>{JSON.stringify(dog)}</Text>)
        }))
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    welcome: {
        flex: 1,
    },
    style_text: {
        fontSize: 16,
        color: 'black',
    }
})
